import React, { useContext, useEffect, useState } from 'react';
import {Alert, Text, TouchableHighlight, TouchableOpacity, View} from 'react-native';
import {ListItem, CheckBox, Icon, Input, Button} from 'react-native-elements';

import LocaleContext from '../libs/locale';
import { getCurrentNode, nodes, setCurrentNode } from '../libs/nodes';
import AsyncStorage from "@react-native-async-storage/async-storage";

const Nodes = () => {
  const locale = useContext(LocaleContext);
  const [node, setNode] = useState('');
  const [myNodes, setMyNodes]:any = useState([]);
  const [showAdd, setShowAdd]:any = useState(false);
  const [addNodeName, setAddNodeName]:any = useState("");
  const [addNodeIp, setAddNodeIp]:any = useState("");
  const [addNodePort, setAddNodePort]:any = useState("");

  useEffect(() => {
    const work = async () => {
      const node: any = await getCurrentNode();
        console.log(nodes)
        setNode(node.name);
    };
    //初始化时重新赋值新选择的语言
    if (nodes[0][1].toString()!="" && nodes[0][1].length>1){
        nodes[0][1] = locale?._("AutoSearch") as string;
    }
    work();
  }, [node]);
  const getMyNode = async () => {
        // await AsyncStorage.setItem("myNodes","[]");
        const myNodes = await AsyncStorage.getItem("myNodes");
      // console.log("???"+myNodes)
        if(myNodes)
        {
            setMyNodes(JSON.parse(myNodes));
            return ;
        }
        //setMyNodes([["myNode1","http://150.158.176.66:5000"]]);
    }

  useEffect(()=>{
      getMyNode()
  },[node,myNodes])

  const onSet = async (node: string) => {
    setNode(node);
    await setCurrentNode(node);
  };
  const addNewNode = async () => {
      let NodeName = addNodeName;
      console.log(NodeName)
      console.log(NodeName==="")
      if(NodeName === "" )
      {
          NodeName = "myNode"+(setMyNodes.length+1);
      }
      if(JSON.stringify(myNodes).indexOf(NodeName)>0)
      {
          Alert.alert('',locale?._("Node_AlreadyExists"),[{text:locale?._("Assets.send.OK")}])
          return ;
      }
      console.log(addNodeIp.indexOf("http://"))
      if(addNodeIp === "" || ( addNodeIp.indexOf("http://")!=0 && addNodeIp.indexOf("https://")!=0 ))
      {
          Alert.alert('',locale?._("Node_IPErrorPrompt"),[{text:locale?._("Assets.send.OK")}]);
          return ;
      }
      if(addNodePort=="")
      {
          Alert.alert('',locale?._("Node_PortErrorPrompt"),[{text:locale?._("Assets.send.OK")}]);
          return ;
      }
      if(JSON.stringify(myNodes).indexOf(addNodeIp+":"+addNodePort) > 0)
      {
          Alert.alert(addNodeIp+":"+addNodePort+"already exists");
          return ;
      }

      let myNodesTemp:any = myNodes;
      myNodesTemp.push([NodeName,addNodeIp+":"+addNodePort]);
      await AsyncStorage.setItem("myNodes",JSON.stringify(myNodesTemp));
      await getMyNode();
      setShowAdd(false);
  }
  const removeMyNode = async (removeNode:any) => {
      let myNodesTemp:any = myNodes;
      console.log(myNodesTemp)
      let index = myNodesTemp.findIndex((n: any) => n===removeNode)
      myNodesTemp.splice(index,1)
      await AsyncStorage.setItem("myNodes",JSON.stringify(myNodesTemp));
      if(node == removeNode[0])
      {
          await onSet("node_random")
      }
  }
  return (
      !node ?
        <></> :
        <View style={{width:"100%",height:"100%"}}>
            {
                nodes.map((n, index) => (
                    <TouchableHighlight underlayColor={"#000000cc"} key={index} onPress={() => onSet(n[0])}>
                        <ListItem bottomDivider key={n[1]}>
                            <CheckBox
                                center
                                checkedIcon='dot-circle-o'
                                uncheckedIcon='circle-o'
                                size={18}
                                checked={node === n[0]}
                                containerStyle={{margin: 0, padding: 0}}
                                checkedColor='#7460E3FF'
                                onPress={() => onSet(n[0])}
                            />
                            <ListItem.Content>
                                {/*{locale?._(`My.nodes.${n[0]}`)}*/}
                                {
                                    n[0] === "node_random" ?
                                        <ListItem.Title>{n[1].replace(":5000", "")}</ListItem.Title>
                                        :
                                        <ListItem.Title>{"POOL" + (index) + "         " + n[1].replace(":5000", "")}</ListItem.Title>
                                }
                            </ListItem.Content>
                        </ListItem>
                    </TouchableHighlight>
                ))
            }
            {
                myNodes.length>0?
                    <View style={{marginTop:50}}>
                        <Text style={{fontSize:15}}>{locale?._("Node_MyNode")}:</Text>
                        {
                            myNodes.map((n:any, index:any) => (
                                <TouchableHighlight
                                                  underlayColor={"#000000cc"}
                                                  key={index}
                                                  onPress={() => onSet(n[0])}
                                                  onLongPress={()=>{
                                                      Alert.alert("Warning","Are you sure you want to delete this node",[
                                                          {
                                                              text: "Delete",
                                                              onPress: () => removeMyNode(n),
                                                          },
                                                          {
                                                              text: "cancle",
                                                          }
                                                      ])
                                                  }}
                                >
                                    <ListItem bottomDivider topDivider key={n[1]}>
                                        <CheckBox
                                            center
                                            checkedIcon='dot-circle-o'
                                            uncheckedIcon='circle-o'
                                            size={18}
                                            checked={node === n[0]}
                                            containerStyle={{margin: 0, padding: 0}}
                                            checkedColor='#7460E3FF'
                                            onPress={() => onSet(n[0])}
                                        />
                                        <ListItem.Content>
                                            {/*{locale?._(`My.nodes.${n[0]}`)}*/}
                                            {
                                                <ListItem.Title>{n[0] +"         " + n[1].split("://")[1]}</ListItem.Title>
                                            }
                                        </ListItem.Content>
                                    </ListItem>
                                </TouchableHighlight>
                            ))
                        }
                    </View>
                    :null
            }
            <TouchableHighlight
                underlayColor={"transparent"}
                style={{backgroundColor: "#02CEFF", alignItems: "center", height: 40, justifyContent: "center"}}
                onPress={() => {
                    setShowAdd(true);
                }}
            >
                <Text style={{color: "#fff"}}>{locale?._("Node_AddNode")}</Text>
            </TouchableHighlight>
            {
                showAdd?
                    <TouchableHighlight
                        underlayColor={"transparent"}
                        style={{position:"absolute",left:0,top:0,bottom:0,right:0,zIndex:1,backgroundColor:"#000000cc",justifyContent:"center"}}
                        onPressIn={()=>setShowAdd(false)}
                        // onPress={()=>{
                        //     setShowAdd(false);
                        // }}
                    >
                        <View style={{backgroundColor:"#fff",width:280,borderRadius:15,alignSelf:"center",alignItems:"center"}}>
                            <Text style={{fontSize:20,marginTop:15}}>{locale?._("Node_AddNode")}</Text>
                            <Input
                                placeholder={locale?._("Node_NodeName")}
                                rightIcon={<Icon
                                    name={'eye' }
                                    type='feather'
                                />}
                                onChangeText={value => setAddNodeName(value)}

                            />
                            <Input
                                placeholder={locale?._("Node_NodeIp")}
                                rightIcon={<Icon
                                    name={'eye'}
                                    type='feather'
                                />}
                                onChangeText={value => setAddNodeIp(value)}
                            />
                            <Input
                                keyboardType={"numeric"}
                                placeholder={locale?._("Node_NodePort")}
                                rightIcon={<Icon
                                    name={'eye'}
                                    type='feather'
                                />}
                                onChangeText={value => setAddNodePort(value)}
                            />
                            <Button
                                title={locale?._('ok')}
                                buttonStyle={{ width: 130, height:40,backgroundColor: '#7460E3FF' }}
                                titleStyle={{fontSize:15,width:"80%",height:25}}
                                onPress={addNewNode}
                            />

                        </View>

                    </TouchableHighlight>
                    :null
            }
        </View>


  );
};

export default Nodes;
